#include "monitor.h"
#include "printf_xxx.h"
#include "mos.h"
#include "STC8G_H_GPIO.h"
#include "STC8G_H_EEPROM.h"


__xdata uint16_t count=0;  //ADC读取次数计数
__xdata uint16_t curr=0;   //供电电流Is=加热器平均电流Il_=D*Il^
__xdata uint16_t volt=50000;   //供电电压Us=加热器峰值电压Ul^
//__xdata uint16_t volt_=0;//加热器平均电压Ul_=D*Ul^=D*Us
__xdata uint16_t powr=0;   //加热器平均功率P=D*Ul^*Il^=供电功率=Us*Is
__xdata uint16_t r1v2=0;   //单片机内部1.2V参考电压平均值
__xdata uint16_t Res=0;    //电阻
__xdata uint16_t temp=0;   //温度，0.1度为单位
__xdata uint16_t temp_=0;  //上次温度


void Mon_Init()
{
	P3_MODE_IN_HIZ(GPIO_Pin_0);
	P3_DIGIT_IN_DISABLE(GPIO_Pin_0);
	P5_MODE_IN_HIZ(GPIO_Pin_5);
	P5_DIGIT_IN_DISABLE(GPIO_Pin_5);
    ADC_InitTypeDef ADCx;
    ADCx.ADC_SMPduty = 31;
    ADCx.ADC_Speed = ADC_SPEED_2X1T;
    ADCx.ADC_AdjResult = ADC_RIGHT_JUSTIFIED;
    ADCx.ADC_CsSetup = 0;
    ADCx.ADC_CsHold = 1;
    ADC_Inilize(&ADCx);
    ADC_PowerControl(ENABLE);
    //TODO:开启PCA中断，在中断中更新ADC
}

void update_ADC()
{
    curr -= curr>>4;
    curr += Get_ADCResult(ADC_CH_CURR)<<2;
    volt -= volt>>4;
    volt += Get_ADCResult(ADC_CH_VOLT)<<2;
    if(volt<40000){       //电压过低，立即复位
        IAP_CONTR = 0x60; //电压检测引脚和与串口RX共用，接收到数据，进入下载模式
    }                     //请使用STC-ISP的自定义下载命令功能发送多个00，以检测到电压过低
    r1v2 -= r1v2>>4;
    r1v2 += Get_ADCResult(ADC_CH_R1V2)<<2;
    if(curr<64){ //防止被除数为0错误
        Res = 0;
    }
    Res = (((uint32_t)volt)*(255-PWM_MOS)<<4)/(curr+curr_bias);
    temp_ = temp;
    temp = (Res>>8)*(calib.k&0xff) + Res*(calib.k>>8) + calib.b;
    count++;
    if(count%8==0){
        print_debug();
    }
}

void print_debug()
{
    printf_s("c=");
    printf_mu(5, count);
    printf_s(", PWM=");
    printf_mu(3, PWM_MOS);
    printf_s(", I=");
    printf_mu(5, curr);
    printf_s(", U=");
    printf_mu(5, volt);
    printf_s(", R=");
    printf_mu(5, Res);
    printf_c('\n');
}

void PCA_INT(void) __interrupt PCA_VECTOR __using 0
{
    if(CF){
        CF = 0;
        update_ADC();
    }
}